from odoo import api, fields, models
import datetime


class ResCountryGroupInheritForBasic(models.Model):
    _inherit = 'res.country.group'

    state_ids = fields.Many2many(string='包含省', comodel_name='res.country.state', domain="[('country_id', 'in', country_ids)]",
                                 relation='res_country_group_and_state_rel', column1='group_id', column2='state_id')

    city_ids = fields.Many2many(string='包含市', comodel_name='res.city', domain="[('state_id', 'in', state_ids)]",
                                relation='res_country_group_and_city_rel', column1='group_id', column2='city_id')

    @api.onchange('country_ids')
    def _onchange_country_ids(self):
        if self.country_ids and self.state_ids:
            states_to_remove = self.state_ids.filtered(lambda s: s.country_id.id not in self.country_ids.ids)
            self.state_ids -= states_to_remove

    @api.onchange('state_ids')
    def _onchange_state_ids(self):
        if self.state_ids:
            city_to_remove = self.city_ids.filtered(lambda s: s.state_id.id not in self.state_ids.ids)
            self.city_ids -= city_to_remove

    def action_for_clear_countries(self):
        """清空所有国家"""
        self.ensure_one()
        if self.country_ids:
            return self.write({'country_ids': [(5, 0, 0)],
                               'state_ids': [(5, 0, 0)],
                               'city_ids': [(5, 0, 0)]})

    def action_for_clear_states(self):
        """ 清空所有省份 """
        self.ensure_one()
        if self.state_ids:
            return self.write({'state_ids': [(5, 0, 0)],
                               'city_ids': [(5, 0, 0)]})

    def action_for_clear_cities(self):
        """ 清空所有城市 """
        self.ensure_one()
        if self.city_ids:
            return self.write({'city_ids': [(5, 0, 0)]})

    def action_for_fulfill_states(self):
        """ 填充所有省份 """
        self.ensure_one()
        if self.country_ids:
            state_rcds = self.env['res.country.state'].search([('country_id', 'in', self.country_ids.ids)])
            return self.write({'state_ids': [(6, 0, state_rcds.ids)]})

    def action_for_fulfill_cities(self):
        """ 填充所有市区 """
        self.ensure_one()
        if self.state_ids:
            city_rcds = self.env['res.city'].search([('state_id', 'in', self.state_ids.ids)])
            return self.write({'city_ids': [(6, 0, city_rcds.ids)]})
